package com.jean.com.retrofittest;

import android.content.Context;
import android.os.Message;
import android.widget.Toast;

import rx.Subscriber;

/**
 * Created by jean on 2016/5/11.
 */
public class ProgressSubscribe<T> extends Subscriber<T> implements ProgressCancelListener{
    private SubscriberOnNextListener mSubscriberOnNextListener;
    private Context mContext;
    private ProgressDialogHandler mProgressDialogHandler;
    public ProgressSubscribe(Context context,SubscriberOnNextListener subscriberOnNextListener){
        mSubscriberOnNextListener = subscriberOnNextListener;
        mContext = context;
        mProgressDialogHandler = new ProgressDialogHandler(mContext,this,true);
    }

    @Override
    public void onStart() {
        super.onStart();
        showProgressDialog();
    }

    @Override
    public void onCancelProgress() {
        if(!this.isUnsubscribed()){
            this.unsubscribe();
        }
    }

    @Override
    public void onCompleted() {
        Toast.makeText(mContext, "dialog显示", Toast.LENGTH_SHORT).show();
        dimissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        Toast.makeText(mContext, "error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
        dimissProgressDialog();
    }

    @Override
    public void onNext(T t) {
        mSubscriberOnNextListener.onNext(t);
    }

    private void showProgressDialog(){
        if(mProgressDialogHandler!=null){
            Message msg = new Message();
            msg.what = ProgressDialogHandler.SHOW_PROGRESS_DIALOG;
            mProgressDialogHandler.sendMessage(msg);
        }
    }

    private void dimissProgressDialog(){
        if(mProgressDialogHandler!=null){
            if(mProgressDialogHandler!=null){
                Message msg = new Message();
                msg.what = ProgressDialogHandler.DISMISS_PROGRESS_DIALOG;
                mProgressDialogHandler.sendMessage(msg);
                mProgressDialogHandler = null;
            }
        }
    }
}
